package com.example.webcrawler.controller;

import com.example.webcrawler.model.ApiRequest;
import com.example.webcrawler.service.mpl.HttpsProxyService;
import com.example.webcrawler.service.mpl.WebAnalysisService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.cert.CertificateEncodingException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;

import java.util.Map;


@Controller
public class WebAnalysisController {

    private static final Logger logger = LoggerFactory.getLogger(WebAnalysisController.class);

    @Autowired
    private WebAnalysisService webAnalysisService;

    @Autowired
    private HttpsProxyService httpsProxyService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("url", "");
        model.addAttribute("requests", List.of());
        model.addAttribute("error", null);
        model.addAttribute("getRequestsCount", 0);
        model.addAttribute("postRequestsCount", 0);
        model.addAttribute("successfulRequestsCount", 0);
        model.addAttribute("dynamicRequestsCount", 0);
        return "index";
    }

    @PostMapping("/analyze")
    public String analyzeUrl(@RequestParam String url,
                             @RequestParam(required = false) String username,
                             @RequestParam(required = false) String password,
                             HttpSession session,
                             Model model) {
        try {
            List<ApiRequest> requests = webAnalysisService.analyzeWebsite(url, username, password);

            // 将结果保存到会话中，以便刷新后仍然可用
            session.setAttribute("analysisResults_" + url, requests);

            // 计算统计数据
            long getRequestsCount = requests.stream()
                    .filter(r -> "GET".equals(r.getMethod()))
                    .count();

            long postRequestsCount = requests.stream()
                    .filter(r -> "POST".equals(r.getMethod()))
                    .count();

            long successfulRequestsCount = requests.stream()
                    .filter(r -> r.getStatus() != null && r.getStatus() >= 200 && r.getStatus() < 300)
                    .count();

            long dynamicRequestsCount = requests.stream()
                    .filter(r -> "Dynamic".equals(r.getSource()))
                    .count();

            model.addAttribute("url", url);
            model.addAttribute("requests", requests);
            model.addAttribute("error", null);
            model.addAttribute("getRequestsCount", getRequestsCount);
            model.addAttribute("postRequestsCount", postRequestsCount);
            model.addAttribute("successfulRequestsCount", successfulRequestsCount);
            model.addAttribute("dynamicRequestsCount", dynamicRequestsCount);
        } catch (Exception e) {
            model.addAttribute("url", url);
            model.addAttribute("requests", List.of());
            model.addAttribute("error", "分析失败: " + e.getMessage());
            model.addAttribute("getRequestsCount", 0);
            model.addAttribute("postRequestsCount", 0);
            model.addAttribute("successfulRequestsCount", 0);
            model.addAttribute("dynamicRequestsCount", 0);
        }
        return "index";
    }

    @PostMapping("/api/analyze")
    @ResponseBody
    public Map<String, Object> analyzeUrlApi(@RequestParam String url,
                                             @RequestParam(required = false) String username,
                                             @RequestParam(required = false) String password) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<ApiRequest> requests = webAnalysisService.analyzeWebsite(url, username, password);

            result.put("success", true);
            result.put("requests", requests);
            result.put("error", null);
        } catch (Exception e) {
            result.put("success", false);
            result.put("requests", List.of());
            result.put("error", "分析失败: " + e.getMessage());
        }
        return result;
    }
    /**
     * 下载CA证书
     */
    @GetMapping("/api/certificate/download")
    public ResponseEntity<Resource> downloadCertificate() {
        try {
            // 获取CA证书
            java.security.cert.X509Certificate caCert = httpsProxyService.getCACertificate();
            if (caCert == null) {
                return ResponseEntity.notFound().build();
            }

            // 将证书转换为PEM格式
            String certPem = "-----BEGIN CERTIFICATE-----\n" +
                    Base64.getEncoder().encodeToString(caCert.getEncoded()) +
                    "\n-----END CERTIFICATE-----\n";

            // 创建输入流
            InputStream inputStream = new ByteArrayInputStream(certPem.getBytes());

            // 创建资源
            InputStreamResource resource = new InputStreamResource(inputStream);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=webcrawler-ca.crt");
            headers.add(HttpHeaders.CONTENT_TYPE, "application/x-x509-ca-cert");

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(certPem.getBytes().length)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (CertificateEncodingException e) {
            logger.error("证书编码错误: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().build();
        } catch (Exception e) {
            logger.error("下载证书时出错: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 检查证书状态
     */
    @GetMapping("/api/certificate/status")
    @ResponseBody
    public Map<String, Object> getCertificateStatus() {
        Map<String, Object> result = new HashMap<>();
        try {
            java.security.cert.X509Certificate caCert = httpsProxyService.getCACertificate();
            if (caCert != null) {
                result.put("success", true);
                result.put("message", "证书已生成，可以下载并安装到系统或浏览器中");
            } else {
                result.put("success", false);
                result.put("message", "证书未生成，请稍后重试");
            }
        } catch (Exception e) {
            logger.error("检查证书状态时出错: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "检查证书状态时出错: " + e.getMessage());
        }
        return result;
    }

    /**
     * 带调试功能的网站分析
     */
    @PostMapping("/analyze-with-debug")
    public String analyzeWithDebug(@RequestParam String url,
                                   @RequestParam(required = false, defaultValue = "true") boolean headless,
                                   @RequestParam(required = false) String username,
                                   @RequestParam(required = false) String password,
                                   Model model) {
        try {
            List<ApiRequest> requests = webAnalysisService.analyzeWithDebug(url, headless);

            // 计算统计数据
            long getRequestsCount = requests.stream()
                    .filter(r -> "GET".equals(r.getMethod()))
                    .count();

            long postRequestsCount = requests.stream()
                    .filter(r -> "POST".equals(r.getMethod()))
                    .count();

            long successfulRequestsCount = requests.stream()
                    .filter(r -> r.getStatus() != null && r.getStatus() >= 200 && r.getStatus() < 300)
                    .count();

            long dynamicRequestsCount = requests.stream()
                    .filter(r -> "Dynamic".equals(r.getSource()))
                    .count();

            model.addAttribute("url", url);
            model.addAttribute("requests", requests);
            model.addAttribute("error", null);
            model.addAttribute("getRequestsCount", getRequestsCount);
            model.addAttribute("postRequestsCount", postRequestsCount);
            model.addAttribute("successfulRequestsCount", successfulRequestsCount);
            model.addAttribute("dynamicRequestsCount", dynamicRequestsCount);
        } catch (Exception e) {
            model.addAttribute("url", url);
            model.addAttribute("requests", List.of());
            model.addAttribute("error", "分析失败: " + e.getMessage());
            model.addAttribute("getRequestsCount", 0);
            model.addAttribute("postRequestsCount", 0);
            model.addAttribute("successfulRequestsCount", 0);
            model.addAttribute("dynamicRequestsCount", 0);
        }
        return "index";
    }
}
